/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gmail.tanyehzheng.util;

import java.util.List;

/**
 *
 * @author Yeh Zheng
 */
public class PagingSupport {

    private int index = -1;
    private int size = 10;
    private final List list;

    public PagingSupport(List list) {
        if (null == list) {
            throw new NullPointerException("list cannot be null");
        }
        this.list = list;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        if (size <= 0) {
            throw new IllegalArgumentException("size cannot be <= 0");
        }
        this.size = size;
    }

    public int maxSize() {
        return list.size();
    }

    public List getPage() {
        if(isBeforeFirst() || 
                isAfterLast()){
            throw new IllegalStateException("Invalid page");
        }
        return list.subList(index, Math.min(maxSize(), index + getSize()));
    }

    public boolean next() {
        if (isBeforeFirst()) {
            index = 0;
        } else if (getLastIndex() == index) {
            afterLast();
        } else {
            index = Math.min(getLastIndex(), index + getSize());
        }
        return !isAfterLast();
    }

    public boolean prev() {
        if(isBeforeFirst()){
            return false;
        }
        if (isFirst()) {
            beforeFirst();
        } else {
            index = Math.max(0, index - getSize());
        }
        return true;
    }

    public boolean hasNext() {
        return (index + getSize()) < maxSize();
    }

    public boolean hasPrev() {
        return !isFirst() && !isBeforeFirst();
    }

    public boolean isFirst() {
        return 0 == index;
    }

    public boolean isLast() {
        return !hasNext();
    }

    public int getLastIndex() {
        return maxSize() - 1;
    }

    public void first() {
        index = 0;
    }

    public void last() {
        index = Math.max(0, maxSize() - getSize());
    }

    public boolean isBeforeFirst() {
        return -1 == index;
    }

    public boolean isAfterLast() {
        return index >= maxSize();
    }

    public void beforeFirst() {
        index = -1;
    }

    public void afterLast() {
        index = maxSize();
    }
}
